package cn.harry.cabinet.view.fragments

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import cn.harry.cabinet.databinding.FragmentCardManagementBinding
import cn.harry.cabinet.model.entity.Card
import cn.harry.cabinet.utils.logConfigChange
import cn.harry.cabinet.view.adapter.CardAdapter
import cn.harry.cabinet.view.dialog.CardFormDialogFragment
import cn.harry.cabinet.view.dialog.DeleteConfirmationDialogFragment
import cn.harry.cabinet.viewmodel.CardViewModel

class CardManagementFragment : BaseFragment() {
    
    private var _binding: FragmentCardManagementBinding? = null
    private val binding get() = _binding ?: throw IllegalStateException("Fragment binding is null. Fragment may have been destroyed.")
    private lateinit var cardAdapter: CardAdapter
    
    // 使用ViewModel获取真实数据
    private val cardViewModel: CardViewModel by viewModels()
    
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentCardManagementBinding.inflate(inflater, container, false)
        return binding.root
    }
    
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        
        setupRecyclerView()
        setupSearchFunction()
        setupObservers()
        setupRefreshLayout()
        setupAddCardButton()
        setupResetButton()
        setupToggleSearch()
        setupEmptyState()
        
        // 清除搜索框焦点，避免弹出键盘
        clearSearchFocus()
        
        // 初始加载数据
        cardViewModel.refreshCards()
    }
    
    private fun setupRecyclerView() {
        cardAdapter = CardAdapter(
            onEditClick = { card ->
                handleEditCard(card)
            },
            onDeleteClick = { card ->
                handleDeleteCard(card)
            }
        )
        
        _binding?.recyclerView?.apply {
            layoutManager = LinearLayoutManager(context)
            adapter = cardAdapter
            setHasFixedSize(true)
        }
    }
    
    private fun setupSearchFunction() {
        _binding?.let { binding ->
            // 设置搜索框点击事件
            binding.searchEditText.setOnClickListener {
                binding.searchEditText.isFocusable = true
                binding.searchEditText.isFocusableInTouchMode = true
                binding.searchEditText.requestFocus()
            }
            
            binding.searchButton.setOnClickListener {
                val query = binding.searchEditText.text.toString().trim()
                cardViewModel.searchCards(query)
            }
            
            // 添加回车键搜索功能
            binding.searchEditText.setOnEditorActionListener { _, _, _ ->
                binding.searchButton.performClick()
                true
            }
        }
    }
    
    private fun setupObservers() {
        // 观察卡片数据变化
        cardViewModel.cards.observe(viewLifecycleOwner) { cards ->
            cardAdapter.setCards(cards)
            updateEmptyState(cards.isEmpty())
            updateStatistics(cards.size)
            // 停止下拉刷新动画
            _binding?.swipeRefreshLayout?.isRefreshing = false
        }
        
        // 观察总卡片数
        cardViewModel.totalCount.observe(viewLifecycleOwner) { totalCount ->
            updateTotalCount(totalCount)
        }
        
        // 观察加载状态
        cardViewModel.loading.observe(viewLifecycleOwner) { isLoading ->
            _binding?.progressBar?.visibility = if (isLoading) View.VISIBLE else View.GONE
            if (isLoading) {
                _binding?.swipeRefreshLayout?.isRefreshing = true
            } else {
                _binding?.swipeRefreshLayout?.isRefreshing = false
            }
        }
        
        // 观察错误信息
        cardViewModel.error.observe(viewLifecycleOwner) { errorMessage ->
            errorMessage?.let {
                Toast.makeText(context, it, Toast.LENGTH_LONG).show()
            }
            _binding?.swipeRefreshLayout?.isRefreshing = false
        }
    }
    
    private fun setupRefreshLayout() {
        _binding?.swipeRefreshLayout?.setOnRefreshListener {
            cardViewModel.refreshCards()
        }
        
        // 设置刷新提示文字
        _binding?.swipeRefreshLayout?.setColorSchemeResources(
            android.R.color.holo_blue_bright,
            android.R.color.holo_green_light,
            android.R.color.holo_orange_light,
            android.R.color.holo_red_light
        )
    }
    
    private fun setupAddCardButton() {
        _binding?.btnAddCard?.setOnClickListener {
            showAddCardDialog()
        }
    }
    
    private fun setupResetButton() {
        _binding?.btnReset?.setOnClickListener {
            // 清空搜索框
            _binding?.searchEditText?.setText("")
            // 重新加载所有卡片
            cardViewModel.refreshCards()
        }
    }
    
    private fun setupToggleSearch() {
        _binding?.tvToggleSearch?.setOnClickListener {
            toggleSearchCard()
        }
    }
    
    private fun toggleSearchCard() {
        _binding?.let { binding ->
            val isExpanded = binding.searchCard.visibility == View.VISIBLE
            if (isExpanded) {
                // 收起：隐藏查询卡片
                binding.searchCard.visibility = View.GONE
                binding.tvToggleSearch.text = "展开 ▼"
            } else {
                // 展开：显示查询卡片
                binding.searchCard.visibility = View.VISIBLE
                binding.tvToggleSearch.text = "收起 ▲"
            }
        }
    }
    
    private fun clearSearchFocus() {
        _binding?.let { binding ->
            binding.searchEditText.clearFocus()
            val imm = requireActivity().getSystemService(android.content.Context.INPUT_METHOD_SERVICE) as android.view.inputmethod.InputMethodManager
            imm.hideSoftInputFromWindow(binding.searchEditText.windowToken, 0)
        }
    }
    
    private fun setupEmptyState() {
        _binding?.let { binding ->
            // 自定义空状态的图标和文字
            binding.root.findViewById<ImageView>(cn.harry.cabinet.R.id.emptyStateIcon)?.apply {
                setImageResource(cn.harry.cabinet.R.drawable.ic_card)
            }
            binding.root.findViewById<TextView>(cn.harry.cabinet.R.id.emptyStateTitle)?.text = "暂无卡片数据"
            binding.root.findViewById<TextView>(cn.harry.cabinet.R.id.emptyStateMessage)?.text = "点击上方\"添加卡片\"按钮开始添加"
        }
    }
    
    private fun updateEmptyState(isEmpty: Boolean) {
        _binding?.let { binding ->
            binding.emptyView.root.visibility = if (isEmpty) View.VISIBLE else View.GONE
            binding.recyclerView.visibility = if (isEmpty) View.GONE else View.VISIBLE
        }
    }
    
    private fun updateStatistics(filteredCount: Int) {
        _binding?.let { binding ->
            binding.root.findViewById<TextView>(cn.harry.cabinet.R.id.tvFilteredCount)?.text = "筛选结果: $filteredCount"
        }
    }
    
    private fun updateTotalCount(totalCount: Int) {
        _binding?.let { binding ->
            binding.root.findViewById<TextView>(cn.harry.cabinet.R.id.tvTotalCount)?.text = "总数: $totalCount"
        }
    }
    
    private fun handleEditCard(card: Card) {
        showEditCardDialog(card)
    }
    
    private fun handleDeleteCard(card: Card) {
        showDeleteConfirmationDialog(card)
    }
    
    private fun showAddCardDialog() {
        val dialog = CardFormDialogFragment(
            card = null,
            onCardSaved = { newCard ->
                cardViewModel.addCard(newCard) {
                    Toast.makeText(context, "卡片添加成功", Toast.LENGTH_SHORT).show()
                    
                    // 记录添加卡片日志
                    requireContext().logConfigChange(
                        scope = viewLifecycleOwner.lifecycleScope,
                        subType = "CARD_ADD",
                        description = "添加卡片: ${newCard.cardNumber}",
                        oldValue = "",
                        newValue = "卡号: ${newCard.cardNumber}, 名称: ${newCard.name}, 类型: ${newCard.type}"
                    )
                }
            }
        )
        dialog.show(childFragmentManager, "CardFormDialog")
    }
    
    private fun showEditCardDialog(card: Card) {
        val dialog = CardFormDialogFragment(
            card = card,
            onCardSaved = { updatedCard ->
                cardViewModel.updateCard(updatedCard) {
                    Toast.makeText(context, "卡片信息更新成功", Toast.LENGTH_SHORT).show()
                    
                    // 记录更新卡片日志
                    val changes = mutableListOf<String>()
                    if (card.cardNumber != updatedCard.cardNumber) changes.add("卡号: ${card.cardNumber} → ${updatedCard.cardNumber}")
                    if (card.name != updatedCard.name) changes.add("名称: ${card.name} → ${updatedCard.name}")
                    if (card.type != updatedCard.type) changes.add("类型: ${card.type} → ${updatedCard.type}")
                    if (card.remark != updatedCard.remark) changes.add("备注: ${card.remark} → ${updatedCard.remark}")
                    if (card.status != updatedCard.status) changes.add("状态: ${card.status} → ${updatedCard.status}")
                    
                    if (changes.isNotEmpty()) {
                        requireContext().logConfigChange(
                            scope = viewLifecycleOwner.lifecycleScope,
                            subType = "CARD_UPDATE",
                            description = "更新卡片: ${card.cardNumber} - ${changes.joinToString(", ")}",
                            oldValue = "卡号: ${card.cardNumber}, 名称: ${card.name}",
                            newValue = changes.joinToString("\n")
                        )
                    }
                }
            }
        )
        dialog.show(childFragmentManager, "CardFormDialog")
    }
    
    private fun showDeleteConfirmationDialog(card: Card) {
        val dialog = DeleteConfirmationDialogFragment(card.cardNumber) {
            cardViewModel.deleteCard(card) {
                Toast.makeText(context, "卡片删除成功", Toast.LENGTH_SHORT).show()
                
                // 记录删除卡片日志
                requireContext().logConfigChange(
                    scope = viewLifecycleOwner.lifecycleScope,
                    subType = "CARD_DELETE",
                    description = "删除卡片: ${card.cardNumber}",
                    oldValue = "卡号: ${card.cardNumber}, 名称: ${card.name}, 类型: ${card.type}",
                    newValue = "已删除"
                )
            }
        }
        dialog.show(childFragmentManager, "DeleteConfirmationDialog")
    }
    
    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}
